package com.openingedu.mba.service.task.impl;

import java.util.concurrent.BlockingQueue;

import android.util.Log;

import com.openingedu.mba.service.task.TaskCallback;
import com.openingedu.mba.service.task.TaskInvokeCallback;
import com.openingedu.mba.service.task.TaskInvoker;
import com.openingedu.mba.service.task.TaskQueue;

public class TaskQueueConsumer extends TaskInvoker {

	private static final String TAG = TaskQueueConsumer.class.getSimpleName();
	
	private final TaskCallback mCallback;
	private int mThreadId;
	
	public TaskQueueConsumer(TaskCallback callback) {
		super(callback);
		mCallback = callback;
	}

	@Override
	public void executeTask() {
		while (true) {
			BlockingQueue<TaskInvoker> queue = TaskQueue.getTaskQueue();
			synchronized (queue) {
				try {
					if (queue.size() == 0) {
						try {
							Log.i(TAG, "waiting for new callOutSelf request.");
							queue.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
							break;
						}
					}
					TaskInvoker taskInvoker = queue.take();
					mCallback.onStart(taskInvoker);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		getExecutionCallback().sendMessage(mThreadId);
	}

	@Override
	public void setThreadId(int threadId) {
		mThreadId = threadId;
	}
}
